package com.blb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/productfile")
public class ProductFileController {

    private String path="D:\\IdeaProjects\\blb_erp\\target\\classes\\static\\images";
    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("file")MultipartFile file) throws IOException {
        /*获取文件名*/
        String filename = file.getOriginalFilename();
        File file1 = new File(path, filename);
        file.transferTo(new File(path + File.separator + filename));
        uploadImg2(file,filename);
        /*registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/images/**").addResourceLocations("D:\\IdeaProjects\\blb_erp\\src\\main\\resources\\static\\images");*/
        return filename;
    }
    public void uploadImg2(MultipartFile file,String name) throws IOException {

        //创建一个FileOutputStream对象(目标路径)
        FileOutputStream out = new FileOutputStream("D:\\IdeaProjects\\blb_erp\\src\\main\\resources\\static\\images\\" + name);

        //创建一个FileInputStream对象(源文件路径)
        FileInputStream in = new FileInputStream("D:\\IdeaProjects\\blb_erp\\target\\classes\\static\\images\\" + name);
        //进行复制操作
        int len = 0;
        byte[] byts = new byte[1024];
        while ((len = in.read(byts)) != -1) {
            //注意：字节流会直接写入到文件当中，不用刷新缓存
            out.write(byts, 0, len);
        }

        //释放资源
        in.close();
        out.close();

    }
}
